package servlet;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import dao.ProductDAO;
import dao.UserDAO1;
import entity.Product;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@WebServlet(name = "userExport", value = "/user/export")
public class UserExportServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置post请求参数乱码问题
        req.setCharacterEncoding("UTF-8");

        resp.setContentType("application/vnd.ms-excel;charset=utf-8");
        resp.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("用户列表-" + DateUtil.today() + ".xls", "utf-8"));

        String start = req.getParameter("startIndex");
        String end = req.getParameter("endIndex");

        //接收请求参数
        int startIndex = start.equals("") ? 1 : Integer.parseInt(start);
        if(startIndex<=1)
            startIndex = 1;

        int endIndex = end.equals("") ? Integer.MAX_VALUE/10 : Integer.parseInt(end);
        if(startIndex>endIndex)
            return;

        UserDAO1 userDAO1 = new UserDAO1();
        int pageSize = 10;
        int skip = (startIndex - 1) * pageSize;
        int limit = (endIndex - startIndex + 1) * pageSize;
        List<User> list = userDAO1.findPage(skip,limit);

        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("username","用户名");
        writer.addHeaderAlias("age","年龄");
        writer.addHeaderAlias("email","邮箱");
        writer.addHeaderAlias("mobile","手机");
        writer.addHeaderAlias("address","地址");
        writer.addHeaderAlias("status","状态");

        writer.merge(5,"用户列表");

        writer.setOnlyAlias(true); //排除无别名字段
        writer.write(list,true);
        OutputStream out = resp.getOutputStream();
        writer.flush(out,true);
        writer.close();
    }
}
